package Workers;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;

import ServerSide.ClientHandling;

/**
 * @author Avishai Kopeliansky 
 * @ID 066717752
 * @author David Shimshon
 * @ID 038185617
 */
public class Listener extends Thread {
	private LinkedBlockingQueue<String> q;
	private ClientHandling ch;
	private ExecutorService es;
	private boolean flag = true;
	
	/**
	 * @param q The Synchronized Queue with the msgs to deliver
	 * @param ch ClientHandling to recieve to send to the Dispatcher for the broadcasting
	 * @param es The ThreadPool which will run the Dispatcher assignment
	 */
	public Listener(LinkedBlockingQueue<String> q,ClientHandling ch,ExecutorService es)
	{
		this.q = q;
		this.ch = ch;
		this.es = es;
	}
	
	public void run(){
		
		while(flag){
			if(!q.isEmpty()){
				es.submit(new Dispatcher(ch,q.poll()));
			}
		}
	}
	
	/**
	 * @return 0 for approval the shutdown went well
	 */
	public int close(){
		this.flag = false;
		q.clear();
		es.shutdown();
		while(!es.isTerminated()){}
		System.out.println("Closed!");
		return 0;
		
	}


}
